package com.hmyd.hmyd_android.ui;

import java.util.List;

import org.apache.http.cookie.Cookie;

import com.hmyd.hmyd_android.R;
import com.google.common.base.Objects;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.utils.DoShare;
import com.hmyd.hmyd_android.utils.ShakeListenerUtils;
import com.hmyd.hmyd_android.utils.ShakeListenerUtils.ShakeListener;
import com.hmyd.hmyd_android.view.ProgressWebView;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.socialize.bean.SocializeConfig;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.sso.UMSsoHandler;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.TextView;


/**
 * @project com.hmyd.hmyd_android.web
 * @className WebActivity
 * @description
 * @author wasdchenhao
 * @QQ 86135545
 * @createTime 2015年5月20日 上午1:58:32
 * @version V1.0
 * @URL www.oshub.org
 */
@ContentView(R.layout.activity_webview)
public class WebActivity extends BasicActivity {
	private final static int LoginSuccess = 0X0001;

	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;

	private FrameLayout webContent;
	private ProgressWebView webview;
	private String url;
	private String name;
	private String iconUrl;
	private boolean isRightShow;
	private boolean isQRShare;

	private JavaScripdtObject hmyd;

	/* 摇一摇签到    --- start --- */
	private SensorManager sensorManager;
	private ShakeListenerUtils shakeListenerUtils;
	private Vibrator vibrator;

	ShakeListener shakeListener = new ShakeListener() {

		@Override
		public void onShakeListener() {
			if (!hmyd.jumpToLogin()) {
				return;
			}

			// 调用wap摇树接口
			webview.loadUrl("javascript:wave()");
			vibrator.vibrate(300);
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		webContent = (FrameLayout) findViewById(R.id.web_content);

		webview = new ProgressWebView(getApplicationContext(), null);

		webContent.addView(webview);

		// ~~~ 获取参数
		url = getIntent().getStringExtra("url");
		name = getIntent().getStringExtra("name");
		iconUrl = getIntent().getStringExtra("iconUrl");
		isRightShow = getIntent().getBooleanExtra("isRightShow", false);
		isQRShare = getIntent().getBooleanExtra("isQRShare", false);

		home_title_txt.setText(name);
		home_title.setOnTouchListener(touch);
		if (isRightShow) {
			home_right.setVisibility(View.VISIBLE);
			home_right.setBackgroundResource(R.drawable.xiang_icon_fenx);
		} else {
			home_right.setVisibility(View.INVISIBLE);
		}

		hmyd = new JavaScripdtObject();

		new WebViewTask().execute();

		if (url.contains("shake.html")) {
			shakeListenerUtils = new ShakeListenerUtils(this);
			shakeListenerUtils.setShakeListener(shakeListener);
		}
	};

	/* 摇一摇签到    --- end --- */

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void setParams() {

	}

	/**
	 * 保存上次打开前状态
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		webview.saveState(outState);
	}

	@Override
	protected void onResume() {
		super.onResume();

		sensorManager = (SensorManager) getSystemService(Service.SENSOR_SERVICE);
		vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);

		if (shakeListenerUtils != null) {
			sensorManager.registerListener(shakeListenerUtils, 
					sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 
					SensorManager.SENSOR_DELAY_NORMAL);
		}
	}

	/**
	 * 如果使用弹出动画效果，注销感应器
	 */
	@Override
	protected void onPause() {
		super.onPause();
		if (sensorManager != null) {
			sensorManager.unregisterListener(shakeListenerUtils);
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (sensorManager != null) {
			sensorManager.unregisterListener(shakeListenerUtils);
		}
	}

	@Override
	protected void onDestroy() {
		webContent.removeAllViews();

		if (webview != null) {
			webview.setVisibility(View.GONE);
			webview.stopLoading();
			webview.removeAllViews();
			webview.destroy();
			webview = null;
		}

		webContent = null;

		super.onDestroy();
	}

	@Override
	protected void leftButton() {
		if (webview.canGoBack()) { 
//			webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);  
	        webview.goBack();  
		} else {
			AppBasic.getInstance().finishActivity(this);
		}
	}

	@Override
	protected void rightButton() {
		Intent intent = new Intent();
		if (!AppBasic.isLogin) {
			intent.setClass(WebActivity.this, LoginActivity.class);
			startActivity(intent);
		} else {
			if (isQRShare == false){
				if (isRightShow) {
					String iconUrl = getIntent().getStringExtra("iconUrl");
					UMSocialService mController = UMServiceFactory.getUMSocialService("myshare");
					DoShare.initSocialSDK(WebActivity.this, mController, name, url, iconUrl, false);
				}
			} else {
				String iconUrl = getIntent().getStringExtra("iconUrl");
				UMSocialService mController = UMServiceFactory.getUMSocialService("myshare");
				DoShare.initSocialSDK(WebActivity.this, mController, name, AppBasic.app.QRcodeUrl+"&urlToken="+AppBasic.urlToken, iconUrl, false);
			}
		}
		
	}


	class JavaScripdtObject {

		/**
		 * 跳转项目投资页
		 */
		@JavascriptInterface	//Android4.2以后存在一个js接口暴露的问题，所以要加上这句
		public void jumpToInvestment() {
			Intent intent = new Intent();
			intent.putExtra("key", "investment");

			intent.setClass(WebActivity.this, MainActivity.class);
			startActivityForResult(intent, LoginSuccess);
		}

		/**
		 * 跳转登录页
		 */
		@JavascriptInterface
		public boolean jumpToLogin(){
			if (AppBasic.isLogin) {
				return true;
			}

			Intent intent = new Intent();
			intent.putExtra("key", "login");

			intent.setClass(WebActivity.this, LoginActivity.class);
			startActivityForResult(intent, LoginSuccess);

			return false;
		}

		/**
		 * 跳转现金券列表
		 */
		@JavascriptInterface
		public void jumpToCouponList(){
			Intent intent = new Intent();
			if (!AppBasic.isLogin) {
				intent.setClass(WebActivity.this, LoginActivity.class);
			} else {
				intent.setClass(WebActivity.this, CouponListActivity.class);
			}

			startActivityForResult(intent, LoginSuccess);
		}

		/**
		 * 跳转积分列表
		 */
		@JavascriptInterface
		public void jumpToScroeList(){
			Intent intent = new Intent();
			if (!AppBasic.isLogin) {
				intent.setClass(WebActivity.this, LoginActivity.class);
			} else {
				intent.setClass(WebActivity.this, MyScoreActivity.class);
			}

			startActivityForResult(intent, LoginSuccess);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK && requestCode == LoginSuccess) {
			if (AppBasic.cookieStore != null) {
				removeCookie(getApplicationContext());
				saveCookies(getApplicationContext(), url);

				webview.reload();
			}
		}

		UMSsoHandler ssoHandler = SocializeConfig.getSocializeConfig().getSsoHandler(requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	@Override
	public void onPostSuccess(int postId, String msg) {

	}

	@Override
	public void onPostFailure(int postId, String msg) {

	}
	CookieManager cookieManager;

	class WebViewTask extends AsyncTask<Void, Void, Boolean>{

		@Override
		protected void onPreExecute() {
			CookieSyncManager.createInstance(WebActivity.this);
			cookieManager = CookieManager.getInstance();

			if (AppBasic.cookieStore != null) {
				removeCookie(getApplicationContext());
			}

			super.onPreExecute();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			SystemClock.sleep(1000);
			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (AppBasic.cookieStore != null) {
				saveCookies(getApplicationContext(), url);
			}

			// ~~~ 设置数据
			webview.getSettings().setSupportZoom(true);
			webview.getSettings().setBuiltInZoomControls(true);
			webview.getSettings().setJavaScriptEnabled(true);
			// 设置可以访问文件
			webview.getSettings().setAllowFileAccess(true);
			// 设置支持缩放
			webview.getSettings().setBuiltInZoomControls(true);
			webview.getSettings().setDomStorageEnabled(true);

			webview.setDownloadListener(new DownloadListener() {
				@Override
				public void onDownloadStart(String url, String userAgent, String contentDisposition,
						String mimetype, long contentLength) {
					if (url != null && url.startsWith("http://"))
						startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
				}
			});

			webview.setWebViewClient(new WebViewClient() {

				@Override
				public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
					//handler.cancel(); 默认的处理方式，WebView变成空白页     
					//接受证书
					handler.proceed();  
				}
				
				@Override
				public boolean shouldOverrideUrlLoading(WebView view, String loadUrl) {
					if (!TextUtils.isEmpty(loadUrl) && !TextUtils.isEmpty(AppBasic.app.sinaReturnUrl)) {
						if (AppBasic.app.sinaReturnUrl.equalsIgnoreCase(loadUrl)) {
							AppBasic.getInstance().finishActivity(WebActivity.this);
						}
					}
					
					view.loadUrl(loadUrl);
					return true;
				}

				@Override
				public void onPageStarted(WebView view, String url,
						Bitmap favicon) {
					super.onPageStarted(view, url, favicon);
				}

				@Override
				public void onLoadResource(WebView view, String url) {
					// history();
				}
			});

			webview.setWebChromeClient(new WebChromeClient() {
				public void onProgressChanged(WebView view, int progress) {
					//Change
				}
			});

			webview.addJavascriptInterface(hmyd, "hmyd");

			if (URLUtil.isValidUrl(url)) {
				webview.loadUrl(url);
			} else {
				webview.loadDataWithBaseURL(null, url, "text/html", "UTF-8", null);
			}
		}

	}

	/**
	 * 设置cookie
	 * @param context
	 * @param url
	 */
	private void saveCookies(Context context, String url){
		CookieSyncManager.createInstance(context);  
		List<Cookie> cookies = AppBasic.cookieStore.getCookies();
		for (int i = 0; i < cookies.size(); i++) {
			// 保存cookie
			Cookie cookie = cookies.get(i);
			cookieManager = CookieManager.getInstance();

			String domain = cookie.getDomain();
			if (domain.endsWith("hmyd.com")) {
				domain = "hmyd.com";
			} 

			if (domain.endsWith("hmyd.cn")) {
				domain = "hmyd.cn";
			}

			String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + domain;

			cookieManager.setCookie(url, cookieString);
		}
	}

	/**
	 * 清除旧cookie
	 * @param context
	 */
	private void removeCookie(Context context) {
		CookieSyncManager.createInstance(context);  
		CookieManager cookieManager = CookieManager.getInstance(); 
		cookieManager.removeAllCookie();
		CookieSyncManager.getInstance().sync();  
	}

	@Override 
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK 
				&& event.getAction() == KeyEvent.ACTION_DOWN 
				&& event.getRepeatCount() == 0 && webview.canGoBack()) { 
//			webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);  
	        webview.goBack();  
	        return true;  
		} 
		return super.dispatchKeyEvent(event); 
	}
}
